package com.iss.supermarket.LoginUI;

import com.iss.supermarket.util.MessageWindow.MsgWin;
import com.iss.supermarket.util.entity.SpUser;
import com.iss.supermarket.util.repository.UserDao;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import javax.lang.model.element.UnknownAnnotationValueException;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegisterUI extends JFrame{
    //单例模式
    protected static RegisterUI registerUI;
    //定义组件
    private JLabel[] registLabels;
    private JTextField[] registerTextFields;
    private JPasswordField registerPasswordField;
    private JCheckBox PasswordVisible;
    private JButton jButton1;
    private JButton jButton2;

    ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("classpath*:/spring_ioc.xml");
    UserDao userDao = ctx.getBean("UserDao", UserDao.class);

    public RegisterUI(){
        super("注册");

        InitAssembly();
        InitUI();
    }

    private void InitUI(){
        Container container = getContentPane();
        Box verticalBox = Box.createVerticalBox();

        JPanel jPanel1 = new JPanel();
        jPanel1.add(registLabels[0]);
        jPanel1.add(registerTextFields[0]);
        jPanel1.add(registLabels[1]);
        jPanel1.add(registerTextFields[1]);
        verticalBox.add(jPanel1);

        JPanel jPanel2 = new JPanel();
        jPanel2.add(registLabels[2]);
        jPanel2.add(registerTextFields[2]);
        verticalBox.add(jPanel2);

        JPanel jPanel3 = new JPanel();
        jPanel3.add(registLabels[3]);
        jPanel3.add(registerPasswordField);
        jPanel3.add(PasswordVisible);
        verticalBox.add(jPanel3);

        JPanel jPanel4 = new JPanel();
        jPanel4.add(registLabels[4]);
        jPanel4.add(registerTextFields[4]);
        verticalBox.add(jPanel4);

        JPanel jPanel5 = new JPanel();
        jPanel5.add(registLabels[5]);
        jPanel5.add(registerTextFields[5]);
        verticalBox.add(jPanel5);

        JPanel jPanel6 = new JPanel();
        jPanel6.add(jButton2);
        jPanel6.add(jButton1);
        verticalBox.add(jPanel6);

        container.add(verticalBox);
        setSize(600,600);
        setComponentInCenter(this);
        setVisible(true);
    }

    private void InitAssembly(){
        registLabels = new JLabel[6];
        registLabels[0] = new JLabel("姓");
        registLabels[1] = new JLabel("名");
        registLabels[2] = new JLabel("用户名");
        registLabels[3] = new JLabel("密码");
        registLabels[4] = new JLabel("手机号码");
        registLabels[5] = new JLabel("电子邮箱");

        for(int i=0;i<6;++i){
            registLabels[i].setHorizontalAlignment(SwingConstants.LEFT);
            //将”名“标签的对齐方式设置为居中
            if(i == 1)
                registLabels[i].setHorizontalAlignment(SwingConstants.CENTER);
            registLabels[i].setPreferredSize(new Dimension(100,25));
        }

        registerTextFields = new JTextField[6];
        for(int i=0;i<6;++i){
            registerTextFields[i] = new JTextField();
            registerTextFields[i].setHorizontalAlignment(SwingConstants.CENTER);
            if(i == 0 || i == 1){
                    //将”姓“和"名"后的文本框的尺寸设置为宽100，高25
                    registerTextFields[i].setPreferredSize(new Dimension(100, 25));
            }else{
                registerTextFields[i].setPreferredSize(new Dimension(300, 25));
            }
        }

        registerPasswordField = new JPasswordField();
        registerPasswordField.setHorizontalAlignment(SwingConstants.CENTER);
        registerPasswordField.setPreferredSize(new Dimension(220,25));
        char defaultEchoChar = registerPasswordField.getEchoChar();
        PasswordVisible = new JCheckBox();
        PasswordVisible.setText("显示密码");
        PasswordVisible.setHorizontalAlignment(SwingConstants.CENTER);
        PasswordVisible.setPreferredSize(new Dimension(80,25));
        PasswordVisible.addActionListener(e -> {
            if(PasswordVisible.isSelected()){
                registerPasswordField.setEchoChar((char)0);
            }else{
                registerPasswordField.setEchoChar(defaultEchoChar);
            }
        });

        jButton1 = new JButton("注册");
        jButton1.addActionListener(new ButtonAction());
        jButton1.setPreferredSize(new Dimension(100,30));
        jButton1.setFont(new Font("黑体",Font.PLAIN,14));
        jButton2 = new JButton("返回登录");
        jButton2.addActionListener(new ButtonAction());
        jButton2.setPreferredSize(new Dimension(100,30));
        jButton2.setFont(new Font("黑体",Font.PLAIN,14));
    }

    private class ButtonAction implements ActionListener{
        @Override
        public void actionPerformed(ActionEvent e) {

            if("注册".equals(e.getActionCommand())){

                RegisterCheck check = new RegisterCheck();
                if(check.checkUserName() && check.checkUserEmail() && check.checkUserMobile() && check.checkUserPassword()){
                    //根据用户名查询
                    SpUser spUserByName = userDao.queryUserInfoByName(registerTextFields[2].getText());
                    //根据手机号码查询
                    SpUser spUserByMobile = userDao.queryUserInfoByMobile(registerTextFields[4].getText());
                    //根据邮箱查询
                    SpUser spUserByEmail = userDao.queryUserInfoByEmail(registerTextFields[5].getText());

                    //检测用户信息是否已经存在
                    if(spUserByName == null && spUserByEmail == null && spUserByMobile == null){
                        //用户信息不存在
                        //生成UUID
                        String uuid = UUID.randomUUID().toString();
                        //生成创建时间
                        Date date = new Date();
                        DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        String modtime = format.format(date);

                        //创建新的SpUser
                        SpUser spUser = new SpUser();
                        spUser.setNiceName(registerTextFields[0].getText() + registerTextFields[1].getText());
                        spUser.setUserName(registerTextFields[2].getText());
                        spUser.setPassword(registerPasswordField.getPassword().toString());
                        spUser.setMobile(registerTextFields[4].getText());
                        spUser.setEmail(registerTextFields[5].getText());
                        spUser.setUserUuid(uuid);
                        spUser.setModtime(modtime);
                        spUser.setRemark("收银员");
                        spUser.setDelFlag(0);
                        //插入数据库表(基于SpringBoot框架达成)
                        userDao.AddNewSpUser(spUser.getUserName(),
                                spUser.getPassword(),
                                spUser.getMobile(),
                                spUser.getEmail(),
                                spUser.getNiceName(),
                                spUser.getUserUuid(),
                                spUser.getRemark(),
                                spUser.getModtime(),
                                0
                                );
                    MsgWin msgWin = new MsgWin("注册成功，返回登陆后可进行登录");
                    }else{
                        //用户信息以及存在，将标签设置为红色提醒用户，清空输入，返回提示信息
                        MsgWin msgWin = new MsgWin("用户已存在");

                        registerTextFields[2].setText("");
                        registerTextFields[2].setForeground(Color.red);

                        registerTextFields[4].setText("");
                        registerTextFields[4].setForeground(Color.red);

                        registerTextFields[5].setText("");
                        registerTextFields[5].setForeground(Color.red);

                        registerPasswordField.setText("");
                        registerPasswordField.setForeground(Color.red);
                    }
                }
            }else if("返回登录".equals(e.getActionCommand())){
                //此处还有对LoginUI类的引用所有LoginUI类中的资源没有完全释放掉，但是窗体已经不可见，继续用但方法没有办法获得窗体，但此处仍旧使用单例方法获得窗体，原因是在LoginUI中在dispose()前将用于单例方法的对象设置为null
                //此处使用loginUI.setVisible(true)有同样效果
                LoginUI loginUI = LoginUI.getLoginUI();
                registerUI.setDefaultCloseOperation(DISPOSE_ON_CLOSE);
                registerUI = null;
                dispose();
            }
        }
    }

    class RegisterCheck{
        //用户输入的检查类
        private static final String MOBILE_REGEX_EXP = "^((13[0-9])|(14[5,7,9])|(15[0-3,5-9])|(166)|(17[0-9])|(18[0-9])|(19[1,8,9]))\\d{8}$";
        private static final String EMAIL_REGEX_EXP = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
        private static final String PASSWORD_REGEX_EXP = "^([a-z0-9A-Z]){8,14}";

        private boolean checkUserName(){
            if ("".equals(registerTextFields[2].getText())) {
                MsgWin msgWin1 = new MsgWin("用户名不能为空");
                return false;
            }
            return true;
        }

        private boolean checkUserEmail(){
            if("".equals(registerTextFields[5].getText())){
                MsgWin msgWin2 = new MsgWin("邮箱不能为空");
                return false;
            }
            Pattern pattern = Pattern.compile(EMAIL_REGEX_EXP);
            Matcher matcher = pattern.matcher(registerTextFields[5].getText());
            if(!matcher.matches()){
                MsgWin msgWin2 = new MsgWin("邮箱格式错误");
                return false;
            }
            return true;
        }

        private boolean checkUserMobile(){
            if("".equals(registerTextFields[4].getText())){
                MsgWin msgWin3 = new MsgWin("手机号码不能为空");
                return false;
            }
            Pattern pattern = Pattern.compile(MOBILE_REGEX_EXP);
            Matcher matcher = pattern.matcher(registerTextFields[4].getText());
            if(!matcher.matches()){
                MsgWin msgWin3 = new MsgWin("手机号码格式有误");
                return false;
            }
            return  true;
        }

        private boolean checkUserPassword(){
            if("".equals(registerTextFields[3].getText())){
                MsgWin msgWin4 = new MsgWin("请输入密码");
                return false;
            }
            Pattern pattern = Pattern.compile(PASSWORD_REGEX_EXP);
            Matcher matcher = pattern.matcher(registerTextFields[3].getText());
            if(!matcher.matches()){
                MsgWin msgWin = new MsgWin("输入密码应只包含大写字母，小写字母和数字");
                return false;
            }
            return true;
        }

        public RegisterCheck(){}
    }

    private void setComponentInCenter(Component component){
        Dimension UISIZAE = component.getSize();
        Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
        if (UISIZAE.height > screenSize.height)
            UISIZAE.height = screenSize.height;
        if (UISIZAE.width > screenSize.width)
            UISIZAE.width = screenSize.width;
        component.setLocation((screenSize.width - UISIZAE.width) / 2, (screenSize.height - UISIZAE.height) / 2);
    }

    public static synchronized RegisterUI getRegisterUI(){
        if(registerUI == null)
            registerUI = new RegisterUI();
        return registerUI;
    }
}